﻿/*GamesEdit概念测试
*   Version     Date	        Log             writer 
*  ----------------------------------------------------
*   0.1        2008-05-18      大概框架         zxp
*   0.2        2008-05-25      重新设计感念     zxp
*                              确定大体框架  
*   0.3        2008-05-26      基本功能完成     zxp
*   0.4        2008-05-31      xml读取完成
*                              界面调整         zxp
================================================================ */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Collections;
using System.Xml;


namespace GamesEdit
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        //////初始化变量////////
        /// <summary>
        /// fc代码所在目录
        /// </summary>
        string fc目录 = Application.StartupPath + "\\Code\\fc\\";
        /// <summary>
        /// 游戏数据库版本
        /// </summary>
        string GameVer = null;
        /// <summary>
        /// 程序版本
        /// </summary>
        string AppVer = null;
        /// <summary>
        /// 游戏数据库url
        /// </summary>
        Uri GameDatUrl = new Uri("http://www.gamesedit.net/test/Game.data");
        /// <summary>
        /// 程序utl
        /// </summary>
        Uri AppDatUrl;

        /// <summary>
        /// 存储选定的游戏
        /// </summary>
        string FileName;

        private void Form1_Load(object sender, EventArgs e)
        {

            if (File.Exists(Application.StartupPath + "\\Game.data"))
            {
                GameDatLoad();    
            }
            else
            {
                WebClient clientDownload = new WebClient();
                clientDownload.DownloadFile(GameDatUrl, "Game.data");
                clientDownload.Dispose();
                GameDatLoad();
                if (Application.ProductVersion != AppVer)//增加版本判断，有时用户拿到的不是新的，但自动从网站下载game.data是新的，所以不会更新exe文件
                {
                        string FileName = "GamesEdit-" + AppVer + ".exe";
                        DownLoadAll(AppDatUrl, FileName);
                }
            }

            if (Directory.Exists(Application.StartupPath + "\\Code"))
            {
                if(!Directory.Exists(Application.StartupPath + "\\Code\\fc"))
                    Directory.CreateDirectory(Application.StartupPath + "\\Code\\fc");
            }
            else
                Directory.CreateDirectory(Application.StartupPath + "\\Code\\fc");

        }

        /// <summary>
        /// 读取游戏数据库Game.data文件
        /// </summary>
        private void GameDatLoad()
        {
            listView1.Items.Clear();
            XmlDocument doc = new XmlDocument();
            doc.Load("Game.data");
            XmlNodeList XmlInfo = doc.GetElementsByTagName("Info");//读取GameData信息
            if (XmlInfo.Count > 0)
            {
                GameVer = XmlInfo[0].ChildNodes.Item(0).InnerText;
                toolStripStatusLabel4.Text = "游戏数据库版本 V" + GameVer;
                AppVer = XmlInfo[0].ChildNodes.Item(1).InnerText;
                GameDatUrl = new Uri(XmlInfo[0].ChildNodes.Item(2).InnerText);
                AppDatUrl = new Uri(XmlInfo[0].ChildNodes.Item(3).InnerText);
            }

            XmlNodeList XmlData = doc.GetElementsByTagName("Data");

            for (int i = 0; i < XmlData.Count; i++)
            {
                ListViewItem item = new ListViewItem(new string[] { 
               XmlData[i].ChildNodes.Item(0).InnerText, 
                XmlData[i].ChildNodes.Item(1).InnerText});
                listView1.Items.AddRange(new ListViewItem[] { item });
            }  
        }

        private string 取得选中游戏文件名()
        {
            string FileName1=null;
            try
            {
                treeView1.Nodes.Clear();
                listBox1.Items.Clear();
                FileName1 = listView1.SelectedItems[0].Text;

            }
            catch (ArgumentOutOfRangeException)
            {
                //MessageBox.Show("请先选中代码!");
            }


            return FileName1 + ".txt";
            
        
        }

        private void 读取FC代码文件(string FileName)
        {
            StreamReader sr = new StreamReader(fc目录 + FileName, System.Text.Encoding.Default);
            TreeNode newNode = null;
            while (sr.Peek() >= 0)
            {
                string temp1 = sr.ReadLine();
                if(temp1!=null)
                    listBox1.Items.Add(temp1);
                string[] temp2 = temp1.Split(' ');
                if (temp2[0] == "_S")
                    toolStripStatusLabel1.Text = temp2[1];
                else if (temp2[0] == "_G")
                {
                    toolStripStatusLabel3.Text = temp1.Remove(0, 3);//有的游戏名字有空格，直接用temp2[0]名字会不全
                    newNode = new TreeNode(toolStripStatusLabel1.Text + "-" + toolStripStatusLabel3.Text);
                }
                else if (temp2[0] == "_C0")
                    newNode.Nodes.Add(temp1.Remove(0, 3));
                else if (temp2[0] == "_C1")
                    newNode.Nodes.Add(temp1.Remove(0, 3));

            }
            sr.Close();
            treeView1.Nodes.Add(newNode);
            treeView1.Nodes[0].ExpandAll();
        }

        private void 导出游戏列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamWriter wr = new StreamWriter("111.txt");
            for (int i = 0; i < listView1.Items.Count; ++i)
            {
                wr.WriteLine(listView1.Items[i].Text);

            }
            wr.Close();
            MessageBox.Show("完成，导出到了111.txt");
        }

        private void 检查更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WebClient clientDownload = new WebClient();
            clientDownload.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCallback2);
            clientDownload.OpenReadAsync(GameDatUrl);//打开网上的数据库，用的异步读取
            clientDownload.Dispose();
        }

        void OpenReadCallback2(Object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(e.Result);
                XmlNodeList XmlInfo = doc.GetElementsByTagName("Info");//读取GameData信息
                string GameVerNew = XmlInfo[0].ChildNodes.Item(0).InnerText;                   
                string AppVerNew = XmlInfo[0].ChildNodes.Item(1).InnerText;
                GameDatUrl = new Uri(XmlInfo[0].ChildNodes.Item(2).InnerText);
                AppDatUrl = new Uri(XmlInfo[0].ChildNodes.Item(3).InnerText);
                

                if (GameVer != GameVerNew)
                {
                    DownLoadGameDat(GameDatUrl, "Game.data");
                }
                else if (AppVer != AppVerNew)
                {
                    string FileName = "GamesEdit-" + AppVerNew + ".exe";
                    DownLoadAll(AppDatUrl, FileName);
                }
                else
                {
                    MessageBox.Show("已经是最新版了!", "GamesEdit");

                }
            }
            else
                MessageBox.Show(e.Error.Message);
        }

        void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            //下载进度条
            toolStripProgressBar1.Value = e.ProgressPercentage;
        }

        void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //下载完成后执行
            MessageBox.Show("游戏数据更新完成!", "GamesEdit");
            toolStripProgressBar1.Visible = false;
            GameDatLoad();
        }
  
        void DownLoadAll(Uri url, string FileName)
        {
            WebClient clientDownload = new WebClient();
            clientDownload.DownloadFile(url, FileName);//下载程序
            clientDownload.Dispose();
            MessageBox.Show("程序更新完成,自动运行新程序!", "GamesEdit");
            System.Diagnostics.Process.Start(FileName);
            Application.Exit();
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">要下载的资源的 URI</param>
        /// <param name="FileName">要放在本地计算机上的文件的名称。</param>
        void DownLoadGameDat(Uri url, string FileName)
        {
            WebClient clientDownload = new WebClient();
            clientDownload.DownloadProgressChanged += new DownloadProgressChangedEventHandler(OnDownloadProgressChanged);//定义下载进度委托
            clientDownload.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadFileCompleted);//定义下载完成后委托
            clientDownload.DownloadFileAsync(url, FileName);
            toolStripProgressBar1.Visible = true;
            clientDownload.Dispose();
        }

        private void fc版ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DriveInfo[] s = DriveInfo.GetDrives();//取得所有的盘符
            bool Ispsp = true;//找到psp盘符为true 没找到为false
            foreach (DriveInfo drive in s)
            {
                if (drive.DriveType == DriveType.Removable)//是移动硬盘 
                {
                    string psp盘符 = drive.Name;

                    if (Directory.Exists(psp盘符 + "\\FreeCheat\\CODE"))
                    {
                        //string FileName = 取得选中游戏文件名();
                        string FileName = this.FileName;
                        if (FileName != null)
                        {
                            File.Copy(fc目录 + FileName, psp盘符 + "\\FreeCheat\\CODE\\" + FileName, true);
                            MessageBox.Show("拷贝完成!", "GamesEdit");
                        }
                        Ispsp = false;
                        break;
                    }
                }
            }
            if (Ispsp)
                MessageBox.Show("没有找到psp盘符或没安装FC程序。", "GamesEdit");
        }

        private void gamesEdit网站ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://bbs.gamesedit.net/");
        }

        private void 更新说明ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            updata updata = new updata(GameDatUrl.ToString().Remove(GameDatUrl.ToString().Length - 9, 9));
            updata.Show();
        }

        private void 刷新目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*listView1.Items.Clear();
            if (Directory.Exists(fc目录))
            {
                DirectoryInfo selDir = new DirectoryInfo(fc目录);
                foreach (FileInfo d in selDir.GetFiles())
                {
                    if (d.Extension.ToLower() == ".txt")
                    {
                        StreamReader sr = new StreamReader(d.FullName, System.Text.Encoding.Default);
                        string temp3 = "";
                        while (sr.Peek() >= 0)
                        {
                            string temp1 = sr.ReadLine();
                            string[] temp2 = temp1.Split(' ');

                            if (temp2[0] == "_S")
                                temp3 = temp2[1];
                            else if (temp2[0] == "_G")
                            {
                                temp3 += "—" + temp1.Remove(0, 3);//有的游戏名字有空格，直接用temp2[0]名字会不全
                                listBox2.Items.Add(temp3);
                            }
                        }
                        sr.Close();
                    }
                }
            }*/
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            textBox1.Text = null;
            textBox1.ForeColor = Color.Black;
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            if (textBox1.Text == null)
            {
                textBox1.Text = "请输入游戏编号或名字...";
                textBox1.ForeColor = Color.Silver;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            搜索游戏();

        }

        private void 搜索游戏()
        {
            ArrayList 搜索结果 = new ArrayList();
            listView1.Items.Clear();
            if (textBox1.Text != "请输入游戏编号或名字...")
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Game.data");
                string itemname = textBox1.Text;
                XmlNodeList XmlData = doc.GetElementsByTagName("Data");
                for (int i = 0; i < XmlData.Count; i++)
                {
                    if (XmlData[i].InnerText.ToLower().Contains(itemname))
                    {
                        ListViewItem item = new ListViewItem(new string[] { 
                            XmlData[i].ChildNodes.Item(0).InnerText, 
                            XmlData[i].ChildNodes.Item(1).InnerText});
                        listView1.Items.AddRange(new ListViewItem[] { item });
                    }
                }
            }
            else
            {
                GameDatLoad();
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            FileName = 取得选中游戏文件名();
            if (FileName != ".txt")
            {
                if (File.Exists(fc目录 + FileName))
                {
                    读取FC代码文件(FileName);
                }
                else
                {
                    try
                    {
                        string 下载代码 = GameDatUrl.ToString().Remove(GameDatUrl.ToString().Length - 9, 9) + "Code/fc/" + FileName;
                        string 保存地址 = Application.StartupPath + "\\Code\\fc\\" + FileName;
                        WebClient clientDownload = new WebClient();
                        clientDownload.DownloadFile(下载代码, 保存地址);
                        clientDownload.Dispose();
                        读取FC代码文件(FileName);
                    }
                    catch (WebException)
                    {
                        listBox1.Items.Clear();
                        listBox1.Items.Add("下载代码失败");
                    }

                }
            }
        }

        private void 生成xmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader sr = new StreamReader("Game1.data", Encoding.Unicode);
            StreamWriter wr = new StreamWriter("111.txt");
            while (sr.Peek() >= 0)
            {
                string[] temp1 = sr.ReadLine().Split('—');
                wr.WriteLine("<Data>");
                wr.WriteLine("<编号>"+temp1[0]+"</编号>");
                wr.WriteLine(" <游戏名>" + temp1[1] + "</游戏名>");
                wr.WriteLine("</Data>");

            }
            sr.Close();
            wr.Close();

         /*剪贴板,下个版本在增加
          * System.Collections.Specialized.StringCollection myCol = new System.Collections.Specialized.StringCollection();

            myCol.Add(fc目录 + FileName);

            Clipboard.SetFileDropList(myCol);*/

        }

        private void cmf版ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DriveInfo[] s = DriveInfo.GetDrives();//取得所有的盘符
            bool Ispsp = true;//找到psp盘符为true 没找到为false
            foreach (DriveInfo drive in s)
            {
                if (drive.DriveType == DriveType.Removable)//是移动硬盘 
                {
                    string psp盘符 = drive.Name;

                    if (Directory.Exists(psp盘符 + "\\CheatMaster"))
                    {
                        //string FileName = 取得选中游戏文件名();
                        string FileName = this.FileName;//不要用 取得选中游戏文件名 如果用户点了下边的代码预览，游戏列表会丢失当前选中的游戏，用户要复制代码，就需要从新点击游戏，这样很麻烦
                        if (FileName != null)
                        {
                            File.Copy(fc目录 + FileName, psp盘符 + "CheatMaster\\" + FileName.ToString().Remove (FileName.ToString().Length-4,4) + ".cmf", true);
                            MessageBox.Show("拷贝完成!");
                        }
                        Ispsp = false;
                        break;
                    }
                }
            }
            if (Ispsp)
                MessageBox.Show("没有找到psp盘符或没安装CMF程序。","GamesEdit");
        }

        private void 复制代码文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Collections.Specialized.StringCollection myCol = new System.Collections.Specialized.StringCollection();
                myCol.Add(fc目录 + FileName);
                Clipboard.SetFileDropList(myCol);
            }
            catch (System.Runtime.InteropServices.ExternalException)
            {
                MessageBox.Show("未能清空剪贴板，请确定没有其它进程使用。", "GamesEdit");
            }
            catch (ArgumentException)
            {
                MessageBox.Show("文件路径出现错误。","GamesEdit");
            }

        }

        private void contextMenuStrip1_Paint(object sender, PaintEventArgs e)
        {
            //没有选中游戏时，把菜单禁用。
            if (FileName == null)
            {
                复制代码文件ToolStripMenuItem.Enabled = false;
                复制代码ToolStripMenuItem1.Enabled = false;
            }
            else
            {
                复制代码文件ToolStripMenuItem.Enabled = true;
                复制代码ToolStripMenuItem1.Enabled = true;
            }
            
        }

        private void 复制代码ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                string 地址 = fc目录 + FileName;
                StreamReader sr = new StreamReader(地址, Encoding.Default);
                string temp1 = sr.ReadToEnd();
                sr.Close();
                if (temp1 != null)
                    Clipboard.SetText(temp1);
            }
            catch (System.Runtime.InteropServices.ExternalException)
            {
                MessageBox.Show("未能清空剪贴板，请确定没有其它进程使用。","GamesEdit");
            }

        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            //第1次运行时，显示更新说明，方便下载完整代码
            XmlDocument doc = new XmlDocument();
            doc.Load("Game.data");
            XmlNodeList XmlFile = doc.GetElementsByTagName("File");
            if (XmlFile.Count > 0)
            {
                if (XmlFile[0].InnerText == "Yes")
                {
                    updata updata = new updata(GameDatUrl.ToString().Remove(GameDatUrl.ToString().Length - 9, 9));
                    updata.Show();
                    XmlFile[0].InnerText = "No";
                    doc.Save("Game.data");
                }
            }

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
                搜索游戏();
        }
    }
}
